  <template>
  <div>
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="showResults = false"
      />
    </form>
    <!-- 搜索结果的组件 -->
    <results
      v-if="showResults"
      :searchTexts="searchText"
      class="searchresults"
    ></results>
    <!-- 搜索联想的组件 -->
    <lenovo
      :searchText="searchText"
      @search="onSearch"
      v-else-if="searchText"
    ></lenovo>
    <!-- 搜索历史的组件 -->
    <searchhistory @delet="history = $event" :history="history" @searchhistory="onSearch" v-else></searchhistory>
  </div>
</template>
<script>
import lenovo from './searchlenovo/index'
import searchhistory from "./searchlenovo/Searchhistory"
import  results from './searchlenovo/searchresults'
import {setItem,getItem} from "../../utils/localStorag"
import {Searchhistory} from "../../api/user"
import { mapState } from "vuex"
// console.log(mapState,this.user)
export default {
    components:{
        lenovo,
        searchhistory,
        results
    },
    computed:{
      ...mapState(['user'])
    },
    data(){
        return{
            searchText:"",
            showResults:false,
            history:getItem('searchhistory') || [],//搜索历史
            localstore:[]
        }
    },
    methods:{
      
       async onSearch(a){//搜索确定
        console.log(a)
        // console.log(search)
        this.searchText = a
        // 1.最新的数据，保存到数组最前面
        // 2.数组去重
        if (this.history.indexOf(a) !== -1){
          //就是说明，有重复的
          this.history.splice(this.history.indexOf(a),1)
          

        }
        this.localstore.unshift(a)

        
        // 然后我们需要将这个数组，传递到子组件中
        

        // 我们需要将，搜索历史保存到本地存储中，不管是否登录
        setItem('searchhistory',this.localstore)//这里就将数据保存了
        this.loadSearchHistories()
        
            
            this.showResults = true
        },
        onCancel(){
            
        },
        async loadSearchHistories(){
          let newLocalstore = getItem('searchhistory') || [];
          console.log(newLocalstore,this.user)
          if (this.user){
            var {data} = await Searchhistory();
            console.log(data)
            newLocalstore = [...new Set([...newLocalstore,...data.data.keywords])]


          }

              
            // 2.我们需要接口，得到线上的搜索历史
            
            console.log(this.localstore)
            this.history = newLocalstore
        },
        watch:{
       history(){
           setItem('searchhistory',this.history)


       }
          
    }
       
    }
};
</script>
<style scoped>
</style>